package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author likepei
 * @Date 2020/2/21 10:29
 * @Version v1.0
 * @Description 图表的控制器
 */
@RestController
@Slf4j
@RequestMapping("report")
public class ReportController {

    @Reference
    private ReportService reportService;

    //@Reference
    //private MemberService memberService;
    /**
     * 根据开始时间和结束时间查询该时间段的新增会员数量
     * @Author: Liuweipeng
     * @Param:
     * @Return:
     */
    @RequestMapping("findMemberReportByDate")
    public Result findMemberReportByDate(@RequestBody String[] dateArray) {
        try {
            System.out.println(Arrays.toString(dateArray));

            Map<String,Object> map = reportService.findMemberReportByDate(dateArray);

            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (RuntimeException re){
            return new Result(false,re.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }


    /**
     * 运营数据统计报表导出
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){
        try {
            //调用Service，获取统计数据
            Map<String, Object> reportData = reportService.getBusinessReportData();
            //获得报表日期
            String reportDate = (String) reportData.get("reportDate");
            //获取与会员有关数据 (今日、本周、本月、总人数)
            Integer todayNewMember = (Integer) reportData.get("todayNewMember");
            Integer thisWeekNewMember = (Integer) reportData.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) reportData.get("thisMonthNewMember");
            Integer totalMember = (Integer) reportData.get("totalMember");
            //获取与预约有关数据 (今日、本周、本月)
            Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
            //获得到诊相关数据 (今日、本周、本月)
            Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
            //获得套餐热门数据
            List<Map<String,Object>> hotSetmealList = (List<Map<String, Object>>) reportData.get("hotSetmeal");

            //利用POIUtils写入数据到Excel
            InputStream inputStream = ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            //利用流，读Excel文件，构建XSSFWorkbook对象，获取工作表
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取报表日期行
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);
            //获取新增会员及会员总数行
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            //获取本周新增会员及本月新增会员行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);
            //获取今日预约及到诊数行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            //获取本周预约及到诊数行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            //获取本月预约及到诊行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);
            //获取热门套餐行，动态写入数据
            //设置起始行号
            int startRowNumber = 12;
            for (Map<String, Object> hotSetmeal : hotSetmealList) {
                //获取名称, 数量, 占比, 备注
                String name = (String) hotSetmeal.get("name");
                Long setmeal_count = (Long) hotSetmeal.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) hotSetmeal.get("proportion");
                String remark = (String) hotSetmeal.get("remark");

                //指定行号
                row = sheet.getRow(startRowNumber);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                row.getCell(7).setCellValue(remark);

                startRowNumber++; //行号+1
            }


            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");

            workbook.write(out);
            //out.flush();
            out.close();
            workbook.close();

            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 获取运营数据统计信息
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            //调用service, 获取到页面中 需要的所有数据 (Map集合)
            Map<String, Object> map = reportService.getBusinessReportData();
            //获取成功, 返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //获取失败, 返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

    /**
     * 获取套餐的占比信息
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            //调用Service , 得到 套餐占比数据
            List<Map<String,Object>> setmealCount = reportService.findSetmealCount();

            //定义一个集合, 用于存储套餐的名称
            List<String> setmealNames = new ArrayList<>();
            //循环, 得到每一个套餐占比信息
            for (Map<String, Object> setmealMap : setmealCount) {
                //把每一个套餐的名称, 存到到套餐名称的集合中
                setmealNames.add((String) setmealMap.get("name"));
            }

            Map<String, Object> map = new HashMap<>();
            map.put("setmealNames", setmealNames);
            map.put("setmealCount", setmealCount);

            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);

        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
    /**
     *男女会员的占比
     * @return
     */
    @RequestMapping("getMemberSex")
    public Result getMemberSex(){
        try {
            //调用Service , 得到男女会员的占比数据
            List<Map<String,Object>> memberSexCount = reportService.findMemberSexCount();
            //定义一个集合, 用于存储会员的性别
            List<String> memberNames = new ArrayList<>();
            for (Map<String, Object> memberSexMap : memberSexCount) {
                //把会员的性别, 存到到性别的集合中
                memberNames.add((String) memberSexMap.get("name"));
            }
            Map<String, Object> map = new HashMap<>();
            map.put("memberNames",memberNames);
            map.put("memberSexCount",memberSexCount);
            System.out.println(map);
            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
    /**
     * 各个年龄段的占比
     * @return
     */
    @RequestMapping("getMemberAge")
    public Result getMemberAge(){
        try {
            //调用Service , 得到各个年龄段的占比数据
            List<Map<String,Object>> memberAgeCount = reportService.getMemberAge();
            //定义一个集合, 用于存储年龄段
            List<String> ageGroupNames = new ArrayList<>();
            for (Map<String, Object> memberAgeMap : memberAgeCount) {
                //把每一个年龄段 存到到年龄段的集合中
                ageGroupNames.add((String) memberAgeMap.get("name"));
            }
            Map<String, Object> map = new HashMap<>();
            map.put("ageGroupNames",ageGroupNames);
            map.put("memberAgeCount",memberAgeCount);
            System.out.println(map);
            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 获取会员数量信息( 最近12个月)
     * @return
     */
    @RequestMapping("getMemberReport")
    public Result getMemberReport(){
        try {
            //构造月份列表
            //1.获取当前日期 (日历对象)
            Calendar calendar = Calendar.getInstance();
            // 返回到12个月之前的日期
            calendar.add(Calendar.MONTH, -12);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
            List<String> monthList = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                //把当前日历的月份 + 1
                calendar.add(Calendar.MONTH, 1);
                //把月份变化后的当前日期, 存入到 monthList集合中
                Date date = calendar.getTime();
                monthList.add(sdf.format(date));
            }

            //调用Service, 获取月份列表的会员数量
            List<Integer> memberCount = reportService.findMemberCountByMonth(monthList);

            //返回报表数据
            Map<String, Object> map = new HashMap<>();
            map.put("months", monthList);
            map.put("memberCount", memberCount);
            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

}
